package com.yiqi.liebang.feature.people.view;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.rongim.pinyin.CharacterParser;
import com.yiqi.liebang.common.rongim.pinyin.PinyinComparator;
import com.yiqi.liebang.common.rongim.pinyin.SideBar;
import com.yiqi.liebang.common.rongim.ui.SelectableRoundedImageView;

import cn.rongcloud.contactcard.Friend;

import com.yiqi.liebang.entity.bo.PeopleBo;
import com.yiqi.liebang.feature.people.view.adapter.FriendListAdapter;
import com.yiqi.liebang.framework.api.UserApi;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.RongIM;

import static com.suozhang.framework.utils.AppUtil.fullScreen;

public class FriendsListActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    private SelectableRoundedImageView mSelectableRoundedImageView;
    private TextView mNameTextView;
    private TextView mNoFriends;
    private TextView mUnreadTextView;
    private View mHeadView;
    private EditText mSearchEditText;
    private ListView mListView;
    private PinyinComparator mPinyinComparator;
    private SideBar mSidBar;
    private boolean is_select = false;
    /**
     * 中部展示的字母提示
     */
    private TextView mDialogTextView;

    private List<Friend> mFriendList;
    private List<Friend> mFilteredFriendList;
    /**
     * 好友列表的 mFriendListAdapter
     */
    private FriendListAdapter mFriendListAdapter;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser mCharacterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */

    private String mId;
    private String mCacheName;
    private String mUserUid;

    private static final int CLICK_CONTACT_FRAGMENT_FRIEND = 2;
    List<Friend> friends = new ArrayList<>();

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_friends_list;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initSystemParams() {
//        super.initSystemParams();
        fullScreen(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    protected void initView() {


        mSearchEditText = (EditText) findViewById(R.id.search);
        mListView = (ListView) findViewById(R.id.listview);
        mNoFriends = (TextView) findViewById(R.id.show_no_friend);
        mSidBar = (SideBar) findViewById(R.id.sidrbar);
        mDialogTextView = (TextView) findViewById(R.id.group_dialog);
        mSidBar.setTextView(mDialogTextView);
        mNoFriends.setVisibility(View.VISIBLE);
        //设置右侧触摸监听
        mSidBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = mFriendListAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    mListView.setSelection(position);
                }

            }
        });


    }


    @Override
    protected void initData() {
        mUserUid = this.getIntent().getStringExtra("user_id");
        is_select = this.getIntent().getBooleanExtra("is_select", false);
        inits(mUserUid);
    }

    private void inits(String userUid) {

        if (!TextUtils.isEmpty(userUid)) {
            initToolBar(mToolbar, "他的好友", true, true);
            PeopleBo peopleBo = new PeopleBo();
            peopleBo.setUserUid(userUid);
            AM.api().createApiService(UserApi.class)
                    .getOtherFriendList(peopleBo)
                    .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                    .subscribe(new Observer<List<Friend>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            showLoading(d);
                        }

                        @Override
                        public void onNext(List<Friend> friends) {
                            dismissLoading();
                            mFriendList = friends;

                            FriendListAdapter adapter = new FriendListAdapter(FriendsListActivity.this, mFriendList);

                            mListView.setAdapter(adapter);

                            //实例化汉字转拼音类
                            mCharacterParser = CharacterParser.getInstance();
                            mPinyinComparator = PinyinComparator.getInstance();


                            updateFriendsList(mFriendList);
                        }

                        @Override
                        public void onError(Throwable e) {
                            T.showShort(e.getMessage());
                            dismissLoading();
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } else {
            initToolBar(mToolbar, "我的好友", true, true);
            PeopleBo peopleBo = new PeopleBo();
            peopleBo.setUserUid(null);
            AM.api().createApiService(UserApi.class)
                    .getMyFriendList(peopleBo)
                    .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                    .subscribe(new Observer<List<Friend>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            showLoading(d);
                        }

                        @Override
                        public void onNext(List<Friend> friends) {
                            dismissLoading();
                            mFriendList = friends;

                            FriendListAdapter adapter = new FriendListAdapter(FriendsListActivity.this, mFriendList);

                            mListView.setAdapter(adapter);

                            //实例化汉字转拼音类
                            mCharacterParser = CharacterParser.getInstance();
                            mPinyinComparator = PinyinComparator.getInstance();


                            updateFriendsList(mFriendList);
                        }

                        @Override
                        public void onError(Throwable e) {
                            T.showShort(e.getMessage());
                            dismissLoading();
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        }


    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr 需要过滤的 String
     */
    private void filterData(String filterStr) {
        List<Friend> filterDateList = new ArrayList<>();

        try {
            if (TextUtils.isEmpty(filterStr)) {
                filterDateList = mFriendList;
            } else {
                filterDateList.clear();
                for (Friend friendModel : mFriendList) {
                    String name = friendModel.getUserName();
                    String displayName = friendModel.getDisplayName();
                    if (!TextUtils.isEmpty(displayName)) {
                        if (name.contains(filterStr) || mCharacterParser.getSpelling(name).startsWith(filterStr) || displayName.contains(filterStr) || mCharacterParser.getSpelling(displayName).startsWith(filterStr)) {
                            filterDateList.add(friendModel);
                        }
                    } else {
                        if (name.contains(filterStr) || mCharacterParser.getSpelling(name).startsWith(filterStr)) {
                            filterDateList.add(friendModel);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            // 根据a-z进行排序
            Collections.sort(filterDateList, mPinyinComparator);
            mFilteredFriendList = filterDateList;
            mFriendListAdapter.updateListView(filterDateList);
        } catch (Exception e) {
            showMsg(e.getMessage());
        }

    }


    private void updateFriendsList(List<Friend> friendsList) {
        //updateUI fragment初始化和好友信息更新时都会调用,isReloadList表示是否是好友更新时调用
        boolean isReloadList = false;
//        if (mFriendList != null && mFriendList.size() > 0) {
//            mFriendList.clear();
//            isReloadList = true;
//        }
        mFriendList = friendsList;
        if (mFriendList != null && mFriendList.size() > 0) {
            handleFriendDataForSort();
            mNoFriends.setVisibility(View.GONE);
        } else {
            mNoFriends.setVisibility(View.VISIBLE);
            return;
        }

        // 根据a-z进行排序源数据
        Collections.sort(mFriendList, mPinyinComparator);
        if (isReloadList) {
            mSidBar.setVisibility(View.VISIBLE);
            mFriendListAdapter.updateListView(mFriendList);
        } else {
            mSidBar.setVisibility(View.VISIBLE);
            mFriendListAdapter = new FriendListAdapter(this, mFriendList);

            mListView.setAdapter(mFriendListAdapter);
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (is_select) {

                        if (mListView.getHeaderViewsCount() > 0) {
                            toSendCard(mFriendList.get(position - 1));
                        } else {
                            toSendCard(mFriendList.get(position));
                        }

                    } else {
                        if (mListView.getHeaderViewsCount() > 0) {
                            startFriendDetailsPage(mFriendList.get(position - 1));
                        } else {
                            startFriendDetailsPage(mFriendList.get(position));
                        }
                    }

                }
            });


            mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//                    Friend bean = mFriendList.get(position - 1);
//                    startFriendDetailsPage(bean);
                    return true;
                }
            });
            mSearchEditText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (TextUtils.isEmpty(s.toString())) {
                        inits(mUserUid);
                    } else {
                        //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                        try {
                            filterData(s.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                            showMsg("onTextChanged" + e.getMessage());
                        }
                    }


                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (!TextUtils.isEmpty(s.toString())) {

                        try {
                            if (s.length() != 0) {
                                if (mListView.getHeaderViewsCount() > 0) {
                                    mListView.removeHeaderView(mHeadView);
                                }
                            } else {
                                if (mListView.getHeaderViewsCount() == 0) {
                                    mListView.addHeaderView(mHeadView);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showMsg("Exception" + e.getMessage());
                        }

                    }else {

                    }
                }

            });
        }
    }


    private void handleFriendDataForSort() {
        for (Friend friend : mFriendList) {
            if (friend.isExitsDisplayName()) {
                String letters = replaceFirstCharacterWithUppercase(friend.getDisplayNameSpelling());
                friend.setLetters(letters);
            } else {
                String letters = replaceFirstCharacterWithUppercase(friend.getUserNamePY());
                friend.setLetters(letters);
            }
        }
    }

    private String replaceFirstCharacterWithUppercase(String spelling) {
        if (!TextUtils.isEmpty(spelling)) {
            char first = spelling.charAt(0);
            char newFirst = first;
            if (first >= 'a' && first <= 'z') {
                newFirst -= 32;
            }
            return spelling.replaceFirst(String.valueOf(first), String.valueOf(newFirst));
        } else {
            return "#";
        }
    }


    private void startFriendDetailsPage(Friend friend) {
        RongIM.getInstance().startPrivateChat(this, friend.getUserUid(), friend.getUserName());
    }

    private void toSendCard(Friend friend) {
        Intent intent = new Intent();

        intent.putExtra("three", friend);
        this.setResult(RESULT_OK, intent);
        finish();
    }

}
